// 导入 http 模块
import http from 'wechat-http'
/**
 * 配置接口基础路径
 */
http.baseURL = 'https://live-api.itheima.net'
/**
 * 挂载方法到全局
 */
//请求拦截器
http.intercept.response = async ({
  statusCode,
  data,
  config
}) => {
  if (statusCode === 401) {
    if (config.url.includes('/refreshToken')) {
      const pageStack = getCurrentPages()
      const lastPage = pageStack[pageStack.length - 1]
      const redirectURL = lastPage.route
      return wx.redirectTo({
        url: `/pages/login/index?redirectURL=/${redirectURL}`,
      })
    }
    if (!app.refresh_token) {
      return
    }
    const app = getApp()
    const res = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: app.refresh_token
      }
    })
    app.setToken(res.data.token, res.data.refreshToken)
    return http(
      Object.assign(config, {
        // 传递新的 token
        header: {
          Authorization: app.token,
        },
      })
    )

  }
  return data
}
/**
 * 配置响应拦截器
 */
http.intercept.request = (params) => {
  // 这里必须要有返回
  const {
    token
  } = getApp()
  const defaultHeader = {}
  if (token) {
    defaultHeader.Authorization = token
  }
  params.header = Object.assign(defaultHeader, params.header)
  return params
}
wx.http = http
/**
 * 模块导出
 */
export default http